﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ERP_RORZE_DLL.Product.Base;
using ERP_RORZE_DLL.Product.DAO;
using ERP_RORZE_DLL.Product.database;
using System.Text.RegularExpressions;
using ERP_RORZE_PERMISSION.Base;
using ERP_RORZE_SYSTEM;
using ERP_RORZE_TOOL.Common;
using BaseDAO = ERP_RORZE_TOOL.DBAccess.BaseDAO;
using Utilities = ERP_RORZE_TOOL.Common.Utilities;

namespace ERP_RORZE_PRODUCT.Product.WTS
{
    public partial class frm_LaborWTSAdd : DevExpress.XtraEditors.XtraForm
    {
        DataTable dt;
        ClsWTSDAO clsWTSDAO = new ClsWTSDAO();
        ClsLaborWTSTable b = new ClsLaborWTSTable();
        //DataTable dtStaff = new DataTable();
        DataTable dtMoNo = new DataTable();
        private bool flagLoadDone;
        //private ctrlLaborWTSDetail laborWts;
        public event EventHandler Reload;
        private bool dropDown;
        private bool first = false;

        int InputedOK;
        int InputedNG;
        int MOQty;
        int MachieNG;
        private string moNo = string.Empty;

        INISettings mySetting = new INISettings();
        private SqlConnection myConnection;
        private DataTable dataTable;
        AutoCompleteStringCollection itemMachine = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemStaff = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemMoNo = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemWork = new AutoCompleteStringCollection();
        private LogUtils log;

        public frm_LaborWTSAdd()
        {
            InitializeComponent();
            myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.txtTime.LostFocus += txtTime_LostFocus;
            cbMONo.LostFocus += cbMONo_LostFocus;
            cbStaff.LostFocus += cbStaff_LostFocus;
            cbMachine.LostFocus += cbMachine_LostFocus;
            cbWorkID.LostFocus += cbWorkID_LostFocus;
            log = new LogUtils();
        }

        void cbWorkID_LostFocus(object sender, EventArgs e)
        {
            if (cbWorkID.Items.Count <= 0)
            {
                foreach (string s in cbWorkID.AutoCompleteCustomSource)
                {
                    if (cbWorkID.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cbWorkID.Text = s;
                        break;
                    }
                }

            }
        }

        void cbMachine_LostFocus(object sender, EventArgs e)
        {
            if (cbMachine.Items.Count <= 0)
            {
                foreach (string s in cbMachine.AutoCompleteCustomSource)
                {
                    if (cbMachine.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cbMachine.Text = s;
                        break;
                    }
                }

            }
        }

        void cbStaff_LostFocus(object sender, EventArgs e)
        {
            if (cbStaff.Items.Count <= 0)
            {
                foreach (string s in cbStaff.AutoCompleteCustomSource)
                {
                    if (cbStaff.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cbStaff.Text = s;
                        break;
                    }
                }

            }

            string sql = "SELECT [222_Staff].StaffID, [222_Staff].StaffName from [222_Staff] " +
                         " WHERE [222_Staff].StaffID = N'" + cbStaff.Text + "'";
            dataTable = BaseDAO.ExecuteQuery(sql);
            if (dataTable.Rows.Count > 0)
            {
                lblStaffName.Text = dataTable.Rows[0]["StaffName"].ToString();
            }
            else
            {
                lblStaffName.Text = string.Empty;
            }
        }

        void cbMONo_LostFocus(object sender, EventArgs e)
        {
            if (cbMONo.Text.Trim().Length > 0)
            {
                DataTable dtBusOrder =
                    BaseDAO.ExecuteQuery("Select * from [242_BusOder] where MONo='" + cbMONo.Text + "'");
                if (dtBusOrder.Rows.Count > 0 && (bool) dtBusOrder.Rows[0]["Started"] == false)
                {
                    cbStaff.Focus();
                    lblPartNo.Text = string.Empty;
                    //cbOption.DataSource = null;
                    MessageBox.Show("Đơn hàng này chưa start.");

                    return;
                }
                else if (dtBusOrder.Rows.Count <= 0)
                {
                    cbStaff.Focus();
                    lblPartNo.Text = string.Empty;
                    //cbOption.DataSource = null;
                    MessageBox.Show("Không có đơn hàng này.");

                    return;
                }
                else
                {

                    if (cbMONo.Items.Count <= 0 && !cbMONo.Text.Trim().Equals(string.Empty))
                    {
                        cbMONo.Text = dtBusOrder.Rows[0]["MONo"].ToString();
                        lblPartNo.Text = dtBusOrder.Rows[0]["PartID"].ToString();
                    }
                    else
                    {
                        DataRow[] row = dtMoNo.Select("MONo = '" + cbMONo.Text + "'");
                        if (row.Length > 0)
                        {
                            lblPartNo.Text = row[0]["PartID"].ToString();
                        }
                        else
                        {
                            lblPartNo.Text = string.Empty;
                        }
                    }
                }

                ////get partNo to label by mono
                //string sql = "SELECT [242_MO].MONo, [242_MO].PartID from [242_MO] " +
                //             " WHERE [242_MO].MONo = N'" + cbMONo.Text + "'";
                //dataTable = BaseDAO.ExecuteQuery(sql);
                //if (dataTable.Rows.Count > 0)
                //{
                //    lblPartNo.Text = dataTable.Rows[0]["PartID"].ToString();
                //}
                //else
                //{
                //    lblPartNo.Text = string.Empty;
                //}

                //binda option data by mono
                if (!first)
                {
                    dataTable = clsWTSDAO.GetAllLOptionID(cbMONo.Text.ToString());
                    DataRow r2 = dataTable.NewRow();
                    r2["OptionID"] = "";

                    dataTable.Rows.InsertAt(r2, 0);
                    cbOption.DataSource = dataTable;
                    cbOption.DisplayMember = "OptionID";
                    cbOption.ValueMember = "OptionID";
                }

                //binda option data by mono
                if (moNo.ToUpper() != cbMONo.Text.ToUpper())
                {
                    dataTable = clsWTSDAO.GetAllLOptionID(cbMONo.Text.ToString());
                    DataRow r2 = dataTable.NewRow();
                    r2["OptionID"] = "";

                    dataTable.Rows.InsertAt(r2, 0);
                    cbOption.DataSource = dataTable;
                    cbOption.DisplayMember = "OptionID";
                    cbOption.ValueMember = "OptionID";
                }


                //Kiem tra don hang da hoan thanh hay chua va ngay nhap wts
                DataTable dtCheck =
                    BaseDAO.ExecuteQuery(
                        "Select [242_MO].MONo, [242_MO].Finished, [242_MO].Finishdate, [242_BusOder].Change, [242_BusOder].ChangeDate " +
                        "from [242_MO] inner join [242_BusOder] on [242_BusOder].MONo=[242_MO].MONo  where [242_MO].MONo=N'" +
                        cbMONo.Text + "'");

                if (dtCheck.Rows.Count > 0)
                {

                    try
                    {

                        if ((bool) dtCheck.Rows[0]["Finished"] &&
                            !Utilities.IsNullOrEmpty(dtCheck.Rows[0]["Finishdate"].ToString()) &&
                            DateTime.Compare(dateDate.Value.Date,
                                DateTime.Parse(dtCheck.Rows[0]["Finishdate"].ToString()).Date) > 0)
                        {
                            MessageBox.Show("Ngày hoàn thành đơn hàng này vào ngày: " +
                                            DateTime.Parse(dtCheck.Rows[0]["Finishdate"].ToString())
                                                .Date.ToString("dd/MM/yyyy") +
                                            ". \nVì vậy Input Date không thể lớn hơn ngày này được.");
                            //dateDate.Focus();
                            return;

                        }

                        else if ((bool) dtCheck.Rows[0]["Finished"] &&
                                 Utilities.IsNullOrEmpty(dtCheck.Rows[0]["Finishdate"].ToString()) &&
                                 dtCheck.Select("Change like '%cancel%'").Length > 0 &&
                                 DateTime.Compare(dateDate.Value.Date,
                                     DateTime.Parse(dtCheck.Rows[0]["ChangeDate"].ToString()).Date) > 0)
                        {
                            MessageBox.Show("Đơn hàng này bị hủy vào ngày: " +
                                            DateTime.Parse(dtCheck.Rows[0]["ChangeDate"].ToString())
                                                .Date.ToString("dd/MM/yyyy") +
                                            ". \nVì vậy Input Date không thể lớn hơn ngày này được.");
                            return;
                            //dateDate.Focus();
                        }

                    }
                    catch (Exception)
                    {

                        MessageBox.Show(
                            "Có lỗi khi kiểm tra đơn hàng này, hãy kiểm tra các trường Finished, FinishDate, Change, ChangeDate bảng MO list và BusOrder");
                    }

                }

                first = true;
                moNo = cbMONo.Text;
            }
        }

        void txtTime_LostFocus(object sender, EventArgs e)
        {
            if (cbStaff.Text == "")
            {
                MessageBox.Show("Chưa nhập Staff ID");
                cbStaff.Focus();
            }
            if (IsNumber(txtTime.Text) == false)
            {
                MessageBox.Show("Time phải là kiểu số");
                txtTime.Focus();
                txtTime.Text = "0";
            }
            else
            {
                int Inputed = 0;
                int Total = 0;
                int OverTime = 0;
                dt = clsWTSDAO.GetAllLaborWTSStaff(cbStaff.Text.ToString(), dateDate.Value.Day, dateDate.Value.Month, dateDate.Value.Year);
                foreach (DataRow r in dt.Rows)
                {
                    Inputed = Inputed + int.Parse(r["SumofTime"].ToString());
                }
                Total = Inputed + int.Parse(txtTime.Text);
                DataTable dt2;
                dt2 = clsWTSDAO.GetAllLaborWTOverTimeStaff(cbStaff.Text.ToString(), dateDate.Value.Day, dateDate.Value.Month, dateDate.Value.Year);
                foreach (DataRow r in dt2.Rows)
                {
                    OverTime = int.Parse(r["SumofTime"].ToString());
                }
                txtTotalTime.Text = "" + Total;
                txtInputedTime.Text = "" + Inputed;
                txtOvertime.Text = "" + OverTime;
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frm_LaborWTSInput_Load(object sender, EventArgs e)
        {
            //list Shift
            DataTable dtShift = new DataTable();
            dtShift.Columns.Add("Display");
            dtShift.Columns.Add("Value");
            for (int i = 0; i < 4; i++)
            {
                DataRow rShift = dtShift.NewRow();
                rShift["Display"] = i.ToString();
                rShift["Value"] = "T" + i.ToString();
                dtShift.Rows.Add(rShift);
            }
            cbShift.DataSource = dtShift;
            cbShift.DisplayMember = "Display";
            cbShift.ValueMember = "Value";
            cbShift.SelectedValue = "T0";
            //////list machine
            //DataTable dt1;
            //dt1 = clsWTSDAO.GetAllLMachine();
            //DataRow r = dt1.NewRow();
            //r["MachineID"] = "";


            //dt1.Rows.InsertAt(r, 0);
            //cbMachine.DataSource = dt1;
            //cbMachine.DisplayMember = "MachineID";
            //cbMachine.ValueMember = "MachineID";

            ////list MO Number
            ////DataTable dtMoNo;
            //dtMoNo = clsWTSDAO.GetAllLWTSMONo();
            //DataRow r1 = dtMoNo.NewRow();
            //r1["MONo"] = "";
            //r1["MONo"] = "";
            //dtMoNo.Rows.InsertAt(r1, 0);
            //cbMONo.DataSource = dtMoNo;
            //cbMONo.DisplayMember = "MONo";
            //cbMONo.ValueMember = "MONo";

            ////dtMoNo = dt2;


            //////list MO Number
            ////DataTable dt2;
            ////dt2 = clsWTSDAO.GetAllLWTSMONo();
            ////DataRow r1 = dt2.NewRow();
            ////r1["MONo"] = "";
            ////r1["FullName"] = "";
            ////dt2.Rows.InsertAt(r1, 0);
            ////cbMONo.DataSource = dt2;
            ////cbMONo.DisplayMember = "FullName";
            ////cbMONo.ValueMember = "MONo";



            //////list staff
            ////DataTable dt4;
            ////dt4 = clsWTSDAO.GetAllStaff();
            ////DataRow r3 = dt4.NewRow();
            ////r3["StaffID"] = "";
            ////r3["FullName"] = "";
            ////dt4.Rows.InsertAt(r3, 0);
            ////cbStaff.DataSource = dt4;
            ////cbStaff.DisplayMember = "FullName";
            ////cbStaff.ValueMember = "StaffID";

            ////list staff
            ////DataTable dt;
            //dtStaff = clsWTSDAO.GetAllStaff();
            //DataRow r3 = dtStaff.NewRow();
            //r3["StaffID"] = "";
            //r3["StaffID"] = "";
            //dtStaff.Rows.InsertAt(r3, 0);
            //cbStaff.DataSource = dtStaff;
            //cbStaff.DisplayMember = "StaffID";
            //cbStaff.ValueMember = "StaffID";

            ////dtStaff = dt4;


            //////list work
            //DataTable dt5;
            //dt5 = clsWTSDAO.GetAllWorkLWTS();
            //DataRow r4 = dt5.NewRow();
            //r4["WorkID"] = "";

            //dt5.Rows.InsertAt(r4, 0);
            //cbWorkID.DataSource = dt5;
            //cbWorkID.DisplayMember = "WorkID";
            //cbWorkID.ValueMember = "WorkID";

            BindDataMachine();
            BindDataStaff();
            BindDataMoNo();
            BindDataWork();
            dateDate.Focus();
            flagLoadDone = true;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            btnAdd.Focus();
            if (GetData())
            {

                //kiem tra so luong ok,ng da duoc nhap
                dt = clsWTSDAO.CheckInputVlaborOPT(cbMONo.Text.ToString(), cbOption.Text);
                InputedOK = 0;
                InputedNG = 0;
                foreach (DataRow r in dt.Rows)
                {
                    InputedOK = InputedOK + int.Parse(r["LaborOPTOKQty"].ToString());
                    InputedNG = InputedNG + int.Parse(r["LaborOPTNGQty"].ToString());
                }
                //kiem tra so luong MOQty
                dt = clsWTSDAO.CheckMOQty(cbMONo.Text.ToString());
                MOQty = 0;
                foreach (DataRow r in dt.Rows)
                {
                    MOQty = MOQty + int.Parse(r["MOQty"].ToString());
                }
                //So luong san pham gia cong ngoai may
                dt = clsWTSDAO.ChekMachineNG(cbMONo.Text.ToString());
                MachieNG = 0;
                foreach (DataRow r in dt.Rows)
                {
                    MachieNG = MachieNG + int.Parse(r["SumofNG"].ToString());
                }

                //kiem tra xem nguyen cong ngay co trong MOOption khong
                dt = clsWTSDAO.CheckMOOption(cbMONo.Text.ToString(), cbOption.Text);
                //int i = 0;
                //foreach (DataRow r in dt.Rows)
                //{
                //    i++;
                //}
                if (dt.Rows.Count == 0)
                {
                    MessageBox.Show("Không có dữ liệu trong MOOPtion");
                }
                else if (IsNumber(txtOKQty.Text) == false)
                {
                    MessageBox.Show("OKQty phải là kiểu số");
                }
                else if (IsNumber(txtNGQty.Text) == false)
                {
                    MessageBox.Show("NGOK phải là kiểu số");
                }
                else if (IsNumber(txtTime.Text) == false)
                {
                    MessageBox.Show("Time phải là kiểu số");
                    txtTime.Focus();
                }
                else if (float.Parse(txtTime.Text) <= 0)
                {
                    MessageBox.Show("Time phải lớn 0.");
                    txtTime.Focus();
                }
                else if (IsNumber(txtClampTime.Text) == false)
                {
                    MessageBox.Show("ClampTime phải là kiểu số");
                }
                else if (IsNumber(txtProTime.Text) == false)
                {
                    MessageBox.Show("ProTime phải là kiểu số");
                }
                else
                {
                    try
                    {
                        if ((InputedOK + int.Parse(txtOKQty.Text)) > (MOQty - MachieNG))
                        {
                            MessageBox.Show("Số lượng sản phẩm OK ngoài machine chỉ có: " + (MOQty - MachieNG) + ", số lượng đã nhập trước đó: " + InputedOK + " số lượng trên form: " + int.Parse(txtOKQty.Text));
                        }
                        else if ((InputedNG + int.Parse(txtNGQty.Text)) > MachieNG)
                        {
                            MessageBox.Show("Số lượng sản phẩm NG ngoài machine có: " + MachieNG + ", số lượng NG nhập trước đó là: " + InputedNG + ", số lượng NG nhập trên form là: " + int.Parse(txtNGQty.Text));
                        }
                        else
                        {
                            if ((InputedNG + InputedOK + int.Parse(txtNGQty.Text) + int.Parse(txtOKQty.Text)) == MOQty)
                            {
                                ClsMOOptionTable c = new ClsMOOptionTable();
                                c.MONo = cbMONo.Text.ToString();
                                c.OptionID = cbOption.SelectedValue.ToString();
                                c.Finishdate = dateDate.Value.Date;
                                c.Shift = cbShift.SelectedValue.ToString();
                                clsWTSDAO.UpdateFinishMOOption(c);

                                //write Log
                                log.Table = LogConstant.Table.Product.MOOption;
                                log.Task = LogConstant.Task.Update;
                                log.Description = "MONo: " + c.MONo + "; OptionID: " + c.OptionID + "; Finishdate: " + c.Finishdate +
                                                  "; Shift: " + c.Shift;
                                log.WriteLog();

                                //MessageBox.Show("Đã update vào MOOption thành công");
                            }
                            b.Clamptime = float.Parse(txtClampTime.Text);
                            b.Date = dateDate.Value;
                            b.MachineID = cbMachine.Text.ToString();
                            b.MONo = cbMONo.Text.ToString();
                            b.NGQty = int.Parse(txtNGQty.Text);
                            b.Note1 = txtNote1.Text;
                            b.Note2 = txtNote2.Text;
                            b.OKQty = int.Parse(txtOKQty.Text);
                            b.OptionID = cbOption.SelectedValue.ToString();
                            b.ProTime = float.Parse(txtProTime.Text);
                            b.Shift = cbShift.SelectedValue.ToString();
                            b.StaffID = cbStaff.Text.ToString();
                            b.Time = float.Parse(txtTime.Text);
                            b.WorkID = cbWorkID.Text.ToString();
                            clsWTSDAO.InsertLaborWTS(b);

                            //write Log
                            log.Table = LogConstant.Table.Product.LaborWTS;
                            log.Task = LogConstant.Task.Insert;
                            log.Description = "Date: " + b.Date + "; MONo: " + b.MONo + "; MachineID: " + b.MachineID + "; OptionID: "
                                        + b.OptionID + "; Shift: " + b.Shift + "; WorkID: " + b.WorkID + "; Time: " + b.Time
                                        + "; ProTime: " + b.ProTime + "; ClampTime: " + b.Clamptime;
                            log.WriteLog();

                            //MessageBox.Show("Đã nhập dữ liệu xong");

                            //this.laborWts.BindReload();
                            //cbShift.SelectedValue = cbShift.Text;
                            //cbMONo.Text = string.Empty;
                            //cbOption.Text = string.Empty;
                            cbWorkID.Text = string.Empty;
                            txtInputedTime.Text = "0";
                            txtNGQty.Text = "0";
                            txtNote1.Text = "";
                            txtNote2.Text = "";
                            txtOKQty.Text = "0";
                            txtOvertime.Text = "0";
                            txtProTime.Text = "0";
                            txtClampTime.Text = "0";
                            txtTime.Text = "0";
                            txtTotalTime.Text = "0";
                            cbWorkID.Focus();

                        }
                    }
                    catch
                    {
                        MessageBox.Show("Time, ClampTime, NGQty, OKQty, ProTime phải là kiểu số");
                    }
                }
                //MessageBox.Show(""+InputedOK  +","+ InputedNG +","+MOQty +","+MachieNG);
            }
        }

        public bool IsNumber(string pText)
        {
            Regex regex = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");
            return regex.IsMatch(pText);
        }

        protected override bool ProcessKeyPreview(ref Message m)
        {
            if (m.Msg == 0x0100 && (int)m.WParam == 13)
            {
                this.ProcessTabKey(true);
            }
            return base.ProcessKeyPreview(ref m);
        }

        private void frm_LaborWTSInput_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt)
            {
                if (e.KeyCode == Keys.D)
                {
                    this.btnAdd.PerformClick();
                }
            }
            else if (e.KeyCode == Keys.End)
            {
                btnAdd.Focus();
            }
            else if (e.KeyCode == Keys.Home)
            {
                dateDate.Focus();
            }
        }

        private void cbMONo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (flagLoadDone)
            {

                moNo = cbMONo.Text;
                DataTable dt3;
                dt3 = clsWTSDAO.GetAllLOptionID(cbMONo.Text.ToString());
                DataRow r2 = dt3.NewRow();
                r2["OptionID"] = "";

                dt3.Rows.InsertAt(r2, 0);
                cbOption.DataSource = dt3;
                cbOption.DisplayMember = "OptionID";
                cbOption.ValueMember = "OptionID";

                //get partNo to label by mono
                string sql = "SELECT [242_MO].MONo, [242_MO].PartID from [242_MO] " +
                             " WHERE [242_MO].MONo = N'" + cbMONo.Text + "'";
                dataTable = BaseDAO.ExecuteQuery(sql);
                if (dataTable.Rows.Count > 0)
                {
                    lblPartNo.Text = dataTable.Rows[0]["PartID"].ToString();
                }
                else
                {
                    lblPartNo.Text = string.Empty;
                }

                //Kiem tra don hang da hoan thanh hay chua va ngay nhap wts
                DataTable dtCheck = BaseDAO.ExecuteQuery("Select [242_MO].MONo, [242_MO].Finished, [242_MO].Finishdate, [242_BusOder].Change, [242_BusOder].ChangeDate " +
                                                 "from [242_MO] inner join [242_BusOder] on [242_BusOder].MONo=[242_MO].MONo  where [242_MO].MONo=N'" + cbMONo.Text + "'");

                if (dtCheck.Rows.Count > 0)
                {

                    try
                    {

                        if ((bool)dtCheck.Rows[0]["Finished"] && !Utilities.IsNullOrEmpty(dtCheck.Rows[0]["Finishdate"].ToString()) && DateTime.Compare(dateDate.Value.Date, DateTime.Parse(dtCheck.Rows[0]["Finishdate"].ToString()).Date) > 0)
                        {
                            MessageBox.Show("Ngày hoàn thành đơn hàng này vào ngày: " + DateTime.Parse(dtCheck.Rows[0]["Finishdate"].ToString()).Date.ToString("dd/MM/yyyy") + ". \nVì vậy Input Date không thể lớn hơn ngày này được.");
                            dateDate.Focus();
                        }

                        else if ((bool)dtCheck.Rows[0]["Finished"] && Utilities.IsNullOrEmpty(dtCheck.Rows[0]["Finishdate"].ToString()) && dtCheck.Select("Change like '%cancel%'").Length > 0 && DateTime.Compare(dateDate.Value.Date, DateTime.Parse(dtCheck.Rows[0]["ChangeDate"].ToString()).Date) > 0)
                        {
                            MessageBox.Show("Đơn hàng này bị hủy vào ngày: " + DateTime.Parse(dtCheck.Rows[0]["ChangeDate"].ToString()).Date.ToString("dd/MM/yyyy") + ". \nVì vậy Input Date không thể lớn hơn ngày này được.");
                            dateDate.Focus();
                        }

                    }
                    catch (Exception)
                    {

                        MessageBox.Show(
                                "Có lỗi khi kiểm tra đơn hàng này, hãy kiểm tra các trường Finished, FinishDate, Change, ChangeDate bảng MO list và BusOrder");
                    }

                }
            }
        }

        private void cbStaff_SelectedIndexChanged(object sender, EventArgs e)
        {
            //get StaffName to label by StaffID
            string sql = "SELECT [222_Staff].StaffID, [222_Staff].StaffName from [222_Staff] " +
                         " WHERE [222_Staff].StaffID = N'" + cbStaff.Text + "'";
            dataTable = BaseDAO.ExecuteQuery(sql);
            if (dataTable.Rows.Count > 0)
            {
                lblStaffName.Text = dataTable.Rows[0]["StaffName"].ToString();
            }
            else
            {
                lblStaffName.Text = string.Empty;
            }
        }

        private void txtNote2_MouseDown(object sender, MouseEventArgs e)
        {
            ((TextBox)sender).SelectAll();
        }

        private void txtNote2_Enter(object sender, EventArgs e)
        {
            ((TextBox)sender).SelectAll();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            // Add controls for which Arrow keys => focus is not required.
            if ((!dropDown && (ActiveControl is TextBox || ActiveControl is System.Windows.Forms.ComboBox || ActiveControl is System.Windows.Forms.DateTimePicker)))
            {
                switch (keyData)
                {
                    case Keys.Up:
                        //case Keys.Down:

                        //bool forward = (keyData == Keys.Down);
                        if (this.ProcessTabKey(false))
                        {
                            return true;
                        }

                        break;
                }
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void cbShift_DropDown(object sender, EventArgs e)
        {
            dropDown = true;
            System.Windows.Forms.ComboBox combo = sender as System.Windows.Forms.ComboBox;

            if (combo.Items.Count <= 0)
            {
                Cursor.Current = Cursors.WaitCursor;
                switch (combo.Name)
                {
                    case "cbMONo":
                        foreach (var item in itemMoNo)
                        {
                            cbMONo.Items.Add(item.ToString());
                        }
                        break;
                    case "cbStaff":
                        foreach (var item in itemStaff)
                        {
                            cbStaff.Items.Add(item.ToString());

                        }
                        break;
                    case "cbWorkID":
                        foreach (var item in itemWork)
                        {
                            cbWorkID.Items.Add(item.ToString());

                        }
                        break;
                    case "cbMachine":
                        foreach (var item in itemMachine)
                        {
                            cbMachine.Items.Add(item.ToString());

                        }
                        break;

                }
                Cursor.Current = Cursors.Default;
            }
        }

        private void cbShift_DropDownClosed(object sender, EventArgs e)
        {
            dropDown = false;
        }

        private void lblStaffName_MouseDown(object sender, MouseEventArgs e)
        {
            ((TextBox)sender).SelectAll();
        }

        private void BindDataMachine()
        {
            myConnection.Open();
            SqlCommand cmd_sql = myConnection.CreateCommand();
            cmd_sql.CommandType = CommandType.StoredProcedure;
            cmd_sql.CommandText = clsConstantsFuction.ClsFuctionMachine.GetAllLWTS2;
            SqlDataReader dataReader = cmd_sql.ExecuteReader();
            while (dataReader.Read())
            {
                itemMachine.Add(dataReader["MachineID"].ToString());
            }
            dataReader.Close();
            cmd_sql.Dispose();
            myConnection.Close();

            cbMachine.AutoCompleteCustomSource = itemMachine;

        }

        private void BindDataStaff()
        {
            myConnection.Open();
            SqlCommand cmd_sql = myConnection.CreateCommand();
            cmd_sql.CommandText = "SELECT [222_Staff].StaffID FROM [222_Staff]";
            SqlDataReader dataReader = cmd_sql.ExecuteReader();
            while (dataReader.Read())
            {
                itemStaff.Add(dataReader["StaffID"].ToString());
            }

            dataReader.Close();
            cmd_sql.Dispose();
            myConnection.Close();
            cbStaff.AutoCompleteCustomSource = itemStaff;

        }

        private void BindDataMoNo()
        {
            myConnection.Open();
            SqlCommand cmd_sql = myConnection.CreateCommand();
            cmd_sql.CommandText = "SELECT [242_MO].MONo FROM [242_MO] where [Started] ='1' AND [Finished] ='0'";
            SqlDataReader dataReader = cmd_sql.ExecuteReader();
            while (dataReader.Read())
            {
                itemMoNo.Add(dataReader["MONo"].ToString());
            }
            dataReader.Close();
            cmd_sql.Dispose();
            myConnection.Close();

            dtMoNo = BaseDAO.ExecuteQuery("SELECT [242_MO].MONo, [242_MO].PartID FROM [242_MO] where [Started] ='1' AND [Finished] ='0'");
            cbMONo.AutoCompleteCustomSource = itemMoNo;

        }

        private void BindDataWork()
        {
            myConnection.Open();
            SqlCommand cmd_sql = myConnection.CreateCommand();
            cmd_sql.CommandText = "SELECT [242_Work].WorkID FROM [242_Work]";
            SqlDataReader dataReader = cmd_sql.ExecuteReader();
            while (dataReader.Read())
            {
                itemWork.Add(dataReader["WorkID"].ToString());
            }
            dataReader.Close();
            cmd_sql.Dispose();
            myConnection.Close();
            cbWorkID.AutoCompleteCustomSource = itemWork;

        }

        private bool GetData()
        {
            //Check valid data

            DataTable dtCheck;
            //Kiem tra don hang da hoan thanh hay chua va ngay nhap wts
            dtCheck = BaseDAO.ExecuteQuery("Select [242_MO].MONo, [242_MO].Finished, [242_MO].Finishdate, [242_BusOder].Change, [242_BusOder].ChangeDate " +
                                           "from [242_MO] inner join [242_BusOder] on [242_BusOder].MONo=[242_MO].MONo  where [242_MO].MONo=N'" + cbMONo.Text + "'");

            DataTable dtBusOrder = BaseDAO.ExecuteQuery("Select * from [242_BusOder] where MONo='" + cbMONo.Text + "'");
            if (dtBusOrder.Rows.Count > 0 && (bool)dtBusOrder.Rows[0]["Started"] == false)
            {
                cbStaff.Focus();
                MessageBox.Show("Đơn hàng này chưa start.");
                return false;

            }
            if (dtCheck.Rows.Count > 0)
            {

                try
                {
                    //if (!(bool)dtCheck.Rows[0]["Finished"] && Utilities.IsNullOrEmpty(dtCheck.Rows[0]["Finishdate"].ToString()) && Utilities.IsNullOrEmpty(dtCheck.Rows[0]["ChangeDate"].ToString()))
                    //{
                    //    MessageBox.Show("Đơn hàng này chưa hoàn thành");
                    //}
                    //else
                    //    if ((bool)dtCheck.Rows[0]["Finished"] && !Utilities.IsNullOrEmpty(dtCheck.Rows[0]["Finishdate"].ToString()) && Utilities.IsNullOrEmpty(dtCheck.Rows[0]["ChangeDate"].ToString()))
                    //    {
                    //        MessageBox.Show("Đơn hàng này đã hoàn thành ngày: " + DateTime.Parse(dtCheck.Rows[0]["Finishdate"].ToString()).ToString("dd/MM/yyyy"));

                    //    }
                    //    else
                    //        if ((bool)dtCheck.Rows[0]["Finished"] && Utilities.IsNullOrEmpty(dtCheck.Rows[0]["Finishdate"].ToString()) && !Utilities.IsNullOrEmpty(dtCheck.Rows[0]["ChangeDate"].ToString()))
                    //        {
                    //            MessageBox.Show("Đơn hàng này đã thay đổi ngày: " + DateTime.Parse(dtCheck.Rows[0]["ChangeDate"].ToString()).ToString("dd/MM/yyyy"));

                    //        }

                    if ((bool)dtCheck.Rows[0]["Finished"] && !Utilities.IsNullOrEmpty(dtCheck.Rows[0]["Finishdate"].ToString()) && DateTime.Compare(dateDate.Value.Date, DateTime.Parse(dtCheck.Rows[0]["Finishdate"].ToString()).Date) > 0)
                    {
                        MessageBox.Show("Ngày hoàn thành đơn hàng này vào ngày: " + DateTime.Parse(dtCheck.Rows[0]["Finishdate"].ToString()).Date.ToString("dd/MM/yyyy") + ". \nVì vậy Input Date không thể lớn hơn ngày này được.");
                        //dateDate.Focus();
                        return false;
                    }

                    else if ((bool)dtCheck.Rows[0]["Finished"] && Utilities.IsNullOrEmpty(dtCheck.Rows[0]["Finishdate"].ToString()) && dtCheck.Select("Change like '%cancel%'").Length > 0 && DateTime.Compare(dateDate.Value.Date, DateTime.Parse(dtCheck.Rows[0]["ChangeDate"].ToString()).Date) > 0)
                    {
                        MessageBox.Show("Đơn hàng này bị hủy vào ngày: " + DateTime.Parse(dtCheck.Rows[0]["ChangeDate"].ToString()).Date.ToString("dd/MM/yyyy") + ". \nVì vậy Input Date không thể lớn hơn ngày này được.");
                        //dateDate.Focus();
                        return false;
                    }

                    //else if ((bool)dtCheck.Rows[0]["Finished"] && Utilities.IsNullOrEmpty(dtCheck.Rows[0]["Finishdate"].ToString()) && DateTime.Compare(dateDate.Value.Date, DateTime.Parse(dtCheck.Rows[0]["ChangeDate"].ToString()).Date) > 0)
                    //{
                    //    DataRow[] row = dtCheck.Select("Change like '%cancel%'");
                    //    MessageBox.Show("ChangeDate đơn hàng này vào ngày: " + DateTime.Parse(dtCheck.Rows[0]["ChangeDate"].ToString()).Date.ToString("dd/MM/yyyy") + ". \nVì vậy Input Date không thể lớn hơn ngày này được.");
                    //    dateDate.Focus();
                    //    return false;
                    //}

                }
                catch (Exception)
                {

                    MessageBox.Show(
                            "Có lỗi khi kiểm tra đơn hàng này, hãy kiểm tra các trường Finished, FinishDate, Change, ChangeDate bảng MO list và BusOrder");
                    return false;
                }

            }

            if (Utilities.IsNullOrEmpty(cbShift.SelectedValue))
            {
                MessageBox.Show("Bạn phải chọn Shift", ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbShift.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(cbMachine.Text))
            {
                MessageBox.Show("Bạn phải chọn MachineID", ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbMachine.Focus();
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [222_Machine] where [MachineID]=N'" + cbMachine.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show("Không có MachineID này!", ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbMachine.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(cbStaff.Text))
            {
                MessageBox.Show("Bạn phải chọn StaffID", ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbStaff.Focus();
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [222_Staff] where [StaffID]=N'" + cbStaff.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show("Không có StaffID này!", ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbStaff.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(cbMONo.Text))
            {
                MessageBox.Show("Bạn phải chọn MONo", ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbMONo.Focus();
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [242_MO] where [MONo]=N'" + cbMONo.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show("Không có MONo này!", ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbMONo.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(cbOption.SelectedValue))
            {
                MessageBox.Show("Bạn phải chọn OptionID", ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbOption.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(cbWorkID.Text))
            {
                MessageBox.Show("Bạn phải chọn WorkID", ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbWorkID.Focus();
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [242_Work] where [WorkID]=N'" + cbWorkID.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show("Không có WorkID này!", ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbWorkID.Focus();
                return false;
            }

            return true;
        }
    }
}